<template>
  <el-form 
    ref="loginFormRef" 
    :model="loginForm" 
    :rules="loginRules" 
    class="login-form"
  >
    <!-- 登录头部 -->
    <slot name="login-head">
      <h2 class="title">欢迎登录</h2>
      <div class="title-tip" v-if="bmWarningTips && isShowBmAlert">{{ bmWarningTips }}</div>
    </slot>

    <!-- 账号密码登录 -->
    <el-form-item 
      class="login-name" 
      prop="username" 
      v-if="loginType === 1"
    >
      <el-input 
        v-model="loginForm.username" 
        id="username" 
        type="text" 
        @keyup.enter="handleLogin" 
        auto-complete="off" 
        placeholder="账号"
      >
        <svg-icon 
          slot="prefix" 
          icon-class="user" 
          class="el-input__icon input-icon"
        />
      </el-input>
    </el-form-item>

    <!-- 密码输入 -->
    <el-form-item 
      class="login-pass" 
      prop="password" 
      v-if="loginType === 1"
    >
      <el-input 
        v-model="loginForm.password" 
        id="password" 
        type="password" 
        @keyup.enter="handleLogin" 
        auto-complete="off" 
        placeholder="密码"
      >
        <svg-icon 
          slot="prefix" 
          icon-class="password" 
          style="font-size:18px" 
          class="el-input__icon input-icon"
        />
      </el-input>
      <el-alert 
        v-show="isShowError" 
        :title="errorMsg" 
        type="error" 
        @close="isShowError = false" 
        show-icon
      />
    </el-form-item>

    <!-- 手机号登录 -->
    <el-form-item 
      class="login-name" 
      prop="phone" 
      v-if="loginType === 2"
    >
      <el-input 
        v-model="loginForm.phone" 
        id="phone" 
        type="text" 
        auto-complete="off" 
        placeholder="手机号"
      >
        <svg-icon 
          slot="prefix" 
          icon-class="user" 
          class="el-input__icon input-icon"
        />
      </el-input>
    </el-form-item>

    <!-- 短信验证码 -->
    <el-form-item 
      class="login-pass" 
      prop="msgCode" 
      v-if="loginType === 2"
    >
      <div style="display: flex;">
        <el-input 
          v-model="loginForm.msgCode" 
          id="msgCode" 
          type="text" 
          auto-complete="off" 
          placeholder="短信验证码" 
          @keyup.enter="handleLogin"
        >
          <svg-icon 
            slot="prefix" 
            icon-class="password" 
            style="font-size:18px" 
            class="el-input__icon input-icon"
          />
        </el-input>
        <el-button 
          @click="sendCode1(loginForm.phone)" 
          :disabled="sendCodeObj.disabled" 
          type="primary" 
          style="margin-left: 10px;"
        >
          {{ sendCodeObj.textContent }}
        </el-button>
      </div>
      <el-alert 
        v-show="isShowError" 
        :title="errorMsg" 
        type="error" 
        @close="isShowError = false" 
        show-icon
      />
    </el-form-item>

    <!-- PIN 码输入（UKey） -->
    <el-form-item 
      class="login-pass" 
      prop="pin" 
      v-if="isUserKey"
    >
      <el-input 
        v-model="loginForm.pin" 
        id="pin" 
        type="password" 
        auto-complete="off" 
        placeholder="PIN码" 
        @keyup.enter="handleLogin"
      >
        <svg-icon 
          slot="prefix" 
          icon-class="key" 
          style="font-size:18px" 
          class="el-input__icon input-icon"
        />
      </el-input>
    </el-form-item>

    <!-- 验证码 -->
    <el-form-item 
      prop="code" 
      v-if="captchaOnOff"
    >
      <el-input 
        v-model="loginForm.code" 
        auto-complete="off" 
        placeholder="验证码" 
        style="width: 63%" 
        @keyup.enter="handleLogin"
      >
        <svg-icon 
          slot="prefix" 
          icon-class="validCode" 
          class="el-input__icon input-icon"
        />
      </el-input>
      <div class="login-code">
        <SIdentify 
          :changeCode.sync="identifyCode" 
          :fontSizeMax="34" 
          :fontSizeMin="38" 
          :contentWidth="100" 
          :contentHeight="36" 
          ref="sidentifyRef"
        />
      </div>
    </el-form-item>

    <!-- 扫码登录 -->
    <ScanQRCode 
      v-if="loginType === 3" 
      ref="scanQRCodeRef" 
      @on-login="handleQRCodeLoginSuccess"
    />

    <!-- 登录选项 -->
    <div>
      <el-checkbox 
        v-model="loginForm.rememberMe" 
        v-if="isHaveRememberPassword" 
        style="margin:0px 0px 25px 0px;"
      >
        记住密码
      </el-checkbox>

      <div style="float: right;margin-left:5px;" v-if="isHaveSmsLogin">
        <el-link type="primary" @click="handleForgetPad">忘记密码</el-link>
      </div>

      <!-- 登录方式切换 -->
      <div style="float: right;margin-left:5px;" v-if="(isHaveSmsLogin || isHaveQRCodeLogin) && loginType !== 1">
        <el-link type="primary" @click="loginType = 1">账号密码登录</el-link>
      </div>
      <div style="float: right;margin-left:5px;" v-if="isHaveSmsLogin && loginType !== 2">
        <el-link type="primary" @click="loginType = 2">验证码登录</el-link>
      </div>
      <div style="float: right;margin-left:5px;" v-if="isHaveQRCodeLogin && loginType !== 3">
        <el-link type="primary" @click="handleQRCodeLogin">扫码登录</el-link>
      </div>
    </div>

    <!-- 登录按钮 -->
    <el-form-item style="width:100%;">
      <el-button 
        v-if="loginType !== 3" 
        :loading="loading" 
        size="medium" 
        type="primary" 
        class="login-btn" 
        style="width:100%;font-size:18px" 
        @click.native.prevent="handleLogin"
      >
        <span v-if="!loading">登 录</span>
        <span v-else>登 录 中...</span>
      </el-button>

      <!-- 注册链接 -->
      <div style="float: right;" v-if="register">
        <router-link class="link-type" :to="'/register'">立即注册</router-link>
      </div>

      <!-- 服务器地址选择 -->
      <div v-if="isShowBaseUrl" class="ipconfig-body">
        <el-select 
          style="width:295px" 
          v-model="baseUrl" 
          size="mini" 
          placeholder="请选择服务器地址" 
          @change="onUrlChange"
        >
          <el-option 
            v-for="(item, index) in baseUrlList" 
            :key="index" 
            :label="item.label" 
            :value="item.value"
          >
            <span style="float: left">
              <el-link 
                v-if="index !== 0" 
                icon="el-icon-edit" 
                type="primary" 
                size="mini" 
                :underline="false" 
                @click.stop="handleEditUrl(item, index)"
              />
              {{ item.value }}
            </span>
            <span style="float: right; color: #8492a6; font-size: 13px">
              {{ item.label || item.value }}
              <el-link 
                v-if="index !== 0" 
                icon="el-icon-delete" 
                type="danger" 
                size="mini" 
                :underline="false" 
                @click.stop="handleDeleteUrl(index)"
              />
            </span>
          </el-option>
        </el-select>
        <el-button 
          style="margin-left:10px" 
          type="primary" 
          size="mini" 
          icon="el-icon-plus" 
          @click.stop="handleEditUrl()"
        />
      </div>
    </el-form-item>

    <!-- 模态窗组件 -->
    <!-- <EditBaseUrlModal 
      ref="editBaseUrlModalRef" 
      @onSave="getBaseUrlList" 
    />
    <ChangePassWord 
      ref="changePassWordRef" 
      @reload="onChangePsw" 
    />
    <RetrievePassWord 
      ref="retrievePassWordRef" 
    /> -->
  </el-form>
</template>

<script setup>
import { ref, reactive, watch, onMounted, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useAuthStore } from '@core/store/user';
import { sendCode } from "../../api/commonApi";
import { getCs, getIsUserKeyByShortName } from "../../api/system/csgl/cszc";
import { encrypt, decrypt } from '../../utils/jsencrypt';
import { useStorage } from '../../utils/storage';
// import EditBaseUrlModal from './EditBaseUrlModal.vue';
// import ChangePassWord from './ChangePassWord.vue';
// import RetrievePassWord from './RetrievePassWord.vue';
import SIdentify from "./components/sidentify.vue";
import ScanQRCode from "./components/scanQRCode.vue";

// 引用模板中的组件
const loginFormRef = ref(null);
const sidentifyRef = ref(null);
const scanQRCodeRef = ref(null);
const editBaseUrlModalRef = ref(null);
const changePassWordRef = ref(null);
const retrievePassWordRef = ref(null);

// 获取路由和存储
const router = useRouter();
const route = useRoute();
const authStore = useAuthStore();
const { getStorage, setStorage } = useStorage();

// 响应式数据
const loginForm = reactive({
  phone: '',
  msgCode: '',
  username: '',
  password: '',
  rememberMe: false,
  pin: '',
  code: '',
  uuid: ''
});

// 验证码验证函数
const validateCode = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入验证码'));
  } else if (value.toUpperCase() !== identifyCode.value.toUpperCase()) {
    callback(new Error('验证码错误'));
  } else {
    callback();
  }
};

const loginRules = reactive({
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  msgCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { validator: validateCode, trigger: 'blur' }
  ]
});

const loginType = ref(1); // 1:账号密码 2:短信验证码 3:扫码
const isUserKey = ref(false);
const identifyCode = ref('');
const errorMsg = ref('');
const isShowError = ref(false);
const loading = ref(false);
const redirect = ref('');
const sendCodeObj = ref({
  timgerId: null,
  disabled: false,
  countdown: 60,
  textContent: '发送验证码'
});

// 从 props 接收参数
const props = defineProps({
  register: {
    type: Boolean,
    default: false
  }
});

// 从全局配置获取参数
const isHaveSmsLogin = ref(window.HC_config.VUE_APP_HAVE_SMSLOGIN || false);
const isHaveQRCodeLogin = ref(window.HC_config.VUE_APP_HAVE_QRCODE_LOGIN || false);
const isShowBaseUrl = ref(window.HC_config.VUE_APP_SHOW_BASE_URL || false);
const isHaveRememberPassword = ref(window.HC_config.VUE_APP_NOTREMEMBERPASSWORD ? false : true);
const bmWarningTips = ref(window.HC_config.VUE_APP_BMJSY || '');
const isShowBmAlert = ref(window.HC_config.VUE_APP_BM_LOGIN_CARD || false);
const captchaOnOff = ref(window.HC_config.VUE_APP_IMGCODE || false);

// 服务器地址相关
const baseUrlList = ref([
  {
    label: '系统默认',
    value: window.HC_config.VUE_APP_BASE_API || process.env.VUE_APP_BASE_API
  }
]);
const baseUrl = ref('');

// 生命周期钩子
onMounted(() => {
  // 检查是否需要重定向
  redirect.value = route.query.redirect || '';
  
  // 获取本地存储的服务器地址
  getBaseUrlList();
  
  // 获取记住的密码
  getCookie();
  
  // 生成验证码
  generateIdentifyCode();
  
  // 如果是SSO登录，直接跳转
  if (window.HC_config.VUE_IS_SSO && !route.query.isDev) {
    window.location.href = window.HC_config.VUE_SSO_URL;
  }
});

onUnmounted(() => {
  // 清除定时器
  if (sendCodeObj.value.timgerId) {
    clearInterval(sendCodeObj.value.timgerId);
  }
});



// 生成验证码
const generateIdentifyCode = () => {
  if (sidentifyRef.value) {
    sidentifyRef.value.refreshCode();
  }
};

// 获取本地存储的服务器地址
const getBaseUrlList = () => {
  const storedList = getStorage('BASE_URL_LIST');
  if (storedList && Array.isArray(storedList)) {
    baseUrlList.value = [...baseUrlList.value, ...storedList];
  }
  
  // 获取当前选中的服务器地址
  const storedUrl = getStorage('local_server_ip');
  baseUrl.value = storedUrl || baseUrlList.value[0].value;
};

// 读取cookie
const getCookie = () => {
  const username = getStorage('username');
  const password = getStorage('password');
  const rememberMe = getStorage('rememberMe');
  
  if (rememberMe && username) {
    loginForm.username = username;
    loginForm.rememberMe = true;
    
    if (password) {
      try {
        loginForm.password = decrypt(password);
      } catch (error) {
        console.error('Failed to decrypt password:', error);
      }
    }
  }
};

// 处理登录
const handleLogin = async () => {
  try {
    // 验证表单
    await loginFormRef.value.validate();
    
    loading.value = true;
    isShowError.value = false;
    
    // 检查是否需要UKey
    if (window.HC_config.VUE_IS_Ukey && loginType.value === 1) {
      const { result } = await getIsUserKeyByShortName({ name: loginForm.username });
      isUserKey.value = result;
      
      if (isUserKey.value) {
        // 加载UKey证书逻辑
        // 实际项目中需要实现UKey证书加载和验证
        // 此处省略具体实现
      }
    }
    
    // 准备登录数据
    let loginData = {};
    let loginMethod = 'loginAction';
    
    if (loginType.value === 1) {
      // 账号密码登录
      loginData = {
        username: loginForm.username,
        password: loginForm.password
      };
    } else if (loginType.value === 2) {
      // 短信验证码登录
      loginData = {
        phone: loginForm.phone,
        code: loginForm.msgCode
      };
      loginMethod = 'loginByMsgAction';
    } else if (loginType.value === 1 && isUserKey.value) {
      // UKey登录
      // 实际项目中需要实现UKey签名和验证
      loginData = {
        username: loginForm.username,
        password: loginForm.password,
        certBase64: '', // UKey证书内容
        signature: ''   // 签名结果
      };
      loginMethod = 'loginByUkeyAction';
    }
    
    // 保存记住密码选项
    if (loginForm.rememberMe) {
      setStorage('username', loginForm.username);
      setStorage('password', encrypt(loginForm.password));
      setStorage('rememberMe', true);
    } else {
      setStorage('username', '');
      setStorage('password', '');
      setStorage('rememberMe', false);
    }
    
    // 调用登录API
    await authStore[loginMethod](loginData);
    
    // 登录成功，跳转到目标页面
    const targetPath = redirect.value || '/';
    router.push(targetPath);
  } catch (error) {
    console.error('Login failed:', error);
    loading.value = false;
    showError(error.message || '登录失败');
    
    // 刷新验证码
    if (captchaOnOff.value) {
      generateIdentifyCode();
    }
  }
};

// 显示错误信息
const showError = (msg) => {
  errorMsg.value = msg;
  isShowError.value = true;
};

// 发送短信验证码
const sendCode1 = async (phone) => {
  if (!phone) {
    showError('请输入手机号');
    return;
  }
  
  if (sendCodeObj.value.disabled) return;
  
  try {
    // 禁用按钮并开始倒计时
    sendCodeObj.value.disabled = true;
    startCountdown();
    
    // 发送验证码
    await sendCode({ phone });
  } catch (error) {
    console.error('Failed to send verification code:', error);
    showError(error.message || '发送验证码失败');
    // 重置倒计时
    resetCountdown();
  }
};

// 开始倒计时
const startCountdown = () => {
  if (sendCodeObj.value.timgerId) {
    clearInterval(sendCodeObj.value.timgerId);
  }
  
  sendCodeObj.value.countdown = 60;
  sendCodeObj.value.textContent = `重新发送(${sendCodeObj.value.countdown}s)`;
  
  sendCodeObj.value.timgerId = setInterval(() => {
    sendCodeObj.value.countdown--;
    sendCodeObj.value.textContent = `重新发送(${sendCodeObj.value.countdown}s)`;
    
    if (sendCodeObj.value.countdown <= 0) {
      resetCountdown();
    }
  }, 1000);
};

// 重置倒计时
const resetCountdown = () => {
  if (sendCodeObj.value.timgerId) {
    clearInterval(sendCodeObj.value.timgerId);
  }
  
  sendCodeObj.value.disabled = false;
  sendCodeObj.value.countdown = 60;
  sendCodeObj.value.textContent = '发送验证码';
};

// 忘记密码
const handleForgetPad = () => {
  retrievePassWordRef.value.show();
};

// 扫码登录
const handleQRCodeLogin = () => {
  loginType.value = 3;
  
  // 延迟调用，确保组件已挂载
  nextTick(() => {
    scanQRCodeRef.value.getLoginQRCode();
  });
};

// 扫码登录成功
const handleQRCodeLoginSuccess = () => {
  console.log('扫码登录成功，准备跳转');
  const targetPath = redirect.value || window.HC_config.APP_ROUTE_FIRST || '/';
  router.push(targetPath);
};

// 监听服务器地址变化
const onUrlChange = () => {
  setStorage('local_server_ip', baseUrl.value);
  window.location.reload();
};

// 处理修改密码成功
const onChangePsw = () => {
  authStore.logOut().then(() => {
    if (window.HC_config.APP_BACK_URL) {
      window.location.href = window.HC_config.APP_BACK_URL;
    } else {
      window.location.href = process.env.VUE_APP_PUBLIC_PATH + 'index';
    }
  });
};

// 删除服务器地址
const handleDeleteUrl = (index) => {
  if (index > 0) { // 不允许删除默认地址
    baseUrlList.value.splice(index, 1);
    setStorage('BASE_URL_LIST', baseUrlList.value.slice(1));
  }
};

// 编辑服务器地址
const handleEditUrl = (formData, urlIndex) => {
  editBaseUrlModalRef.value.show(formData, urlIndex);
};
</script>

<style lang="scss" scoped>
.ipconfig-body {
  display: flex;
  margin-top: 10px;
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
  font-weight: 700;
}

.title-tip {
  color: red;
  font-size: 20px;
  text-align: center;
  position: relative;
  top: -10px;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 45px 25px 30px 25px;
  z-index: 1000;

  .el-input {
    height: 38px;
    font-size: 18px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 20px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial, sans-serif;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;
}

.login-pass {
  margin-top: 30px;
}
</style>